<template>
  <el-dialog
    v-el-drag-dialog="{minWidth: 750, updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :width="setDialogWidth(curWidth)"
    :visible="visible"
    :title="$t('INTELLIGENT_CONNECT')"
    :append-to-body="true"
    @open="open"
    @close="close"
  >
    <template v-slot:title>
      <div class="flex align-start" style="width: calc(100% - 80px)">
        <span class="el-dialog__title mr-30">
          {{ $t('INTELLIGENT_CONNECT') }}
        </span>
        <!-- 步骤条 -->
        <steps-bar :steps="steps" :current="step" />
      </div>
    </template>
    <!-- 业务基本信息显示 -->
    <biz-info v-show="step > 2" :form-data="formData" operate-type="open" />
    <!-- 第一步：基础信息填写 -->
    <step-one v-show="step === 1" ref="stepOne" :re-open-data="rowData" :form-data="formData" />
    <!-- 图形化 -->
    <div v-show="step > 1">
      <div class="font-weight-bold pl-20">{{ $t('INTERMEDIATE_NODE') }}</div>
      <el-divider class="m-0 mt-10 mb-10" />
      <otdr-test-btn
        v-if="step >= 3"
        ref="otdrTestBtn"
        class="w-100 mb-10"
        :form-data="formData"
        @taskChange="taskChange"
      />
      <biz-graphical
        ref="bizGraphical"
        :biz-channel-list="graphicalSegmentList"
        :cable-data="graphicalCableData"
        operate-type="open"
      />
    </div>
    <!-- 第二步：推荐路由选择 -->
    <recommend v-show="step === 2" ref="stepTwo" :form-data="formData" operate-type="open" />
    <!-- 第三步：已选择信息展示 和 OTDR测试 -->
    <step-three v-if="step >= 3" ref="stepThree" :form-data="formData" />
    <template v-slot:footer>
      <el-button @click="close">{{ $t('CANCEL') }}</el-button>
      <el-button v-if="step !== 1" @click="previous">{{ $t('PREVIOUS') }}</el-button>
      <el-button
        v-if="step < 3"
        type="primary"
        :disabled="step === 2 && !formData.routeData"
        @click="next"
      >{{ $t('NEXT') }}</el-button>
      <el-button v-if="step === 3" type="primary" @click="$debounce(save)">{{
        $t('SAVE')
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import bizOpenApi from '@/api/oen/BizOpenApi'
  import { checkAfs, deepClone } from '@/utils/common'
  import StepOne from './components/open/StepOne'
  import Recommend from './components/Recommend'
  import StepThree from './components/open/StepThree'
  import StepsBar from '@/components/StepsBar'
  import BizGraphical from '@/components/BizGraphical'
  import BizInfo from './components/BizInfo'
  import OtdrTestBtn from '@/components/OtdrTestBtn'

  export default {
    components: { StepOne, StepThree, Recommend, StepsBar, BizGraphical, BizInfo, OtdrTestBtn },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        steps: [
          'CONFIG_SERVICE_INFORMATION',
          'SELECT_OPTIMAL_LINK',
          'PRE_COMMISSIONING_INSPECTION',
          'COMPLETE'
        ],
        step: 1,
        formData: {
          bizLevel: 'GENERAL',
          bizName: '',
          resourceCode: '',
          aStationId: null,
          aNodeId: '',
          aPortId: '',
          zStationId: null,
          zNodeId: '',
          zPortId: '',
          segmentList: [],
          aNodeData: {},
          zNodeData: {},
          aPortData: { funcType: '' },
          zPortData: { funcType: '' },
          aPortData2: {},
          zPortData2: {},
          routeData: null,
          channelData: null,
          transDirect: 'DUPLEX',
          functionName: 'manager', // 操作日志需要传此类型，判断是topo还是业务管理里执行的开通
          actionName: 'open', // 操作日志需要传此类型，判断是开通还是恢复前执行的otdr测试
          necessaryCable: [],
          forbiddenCable: [],
          necessaryStation: [],
          forbiddenStation: []
        },
        transTable: {
          // 传输方向NONE("无"),START("A向"),END("Z向"),DUPLEX("双向");
          NONE: 'NONE',
          SEND: 'A',
          RECEIVE: 'Z',
          SEND_RECEIVE: 'DUPLEX'
        },
        graphicalSegmentList: [],
        graphicalCableData: {},
        isOtdrTesting: false
      }
    },
    computed: {
      ...mapGetters(['baseRegionList']),
      curWidth() {
        return this.step > 1 ? '90%' : '1200px'
      }
    },
    watch: {
      'formData.channelData': {
        handler() {
          this.changeGraphical()
        },
        immediate: true,
        deep: true
      }
    },
    beforeDestroy() {
      console.log('beforeDestroy')
    },
    methods: {
      open() {
        this.$nextTick(() => {
          this.$refs.stepOne.$refs.firstForm && this.$refs.stepOne.$refs.firstForm.clearValidate()
        })
        this.step = 1
        this.formData = { ...this.$options.data().formData }
        // 重新开通设置选中站点
        this.$nextTick(() => {
          if (this.rowData.bizId && this.$refs.stepOne) {
            this.$refs.stepOne.aStationChange(this.rowData.startStationId)
            this.$refs.stepOne.zStationChange(this.rowData.endStationId)
            this.formData.bizName = this.rowData.bizName + '-1'
            this.formData.resourceCode = this.rowData.resourceCode
            this.formData.bizLevel = this.rowData.bizLevel
          }
        })
      },
      changeGraphical() {
        // console.log('this.formData', this.formData)
        if (!this.formData.routeData) {
          this.graphicalSegmentList = []
          this.graphicalCableData = {}
        } else {
          const routeSegmentList = this.formData.routeData.segmentList
          const channelData = this.formData.channelData
          routeSegmentList.forEach((i, index) => {
            channelData[0].segmentList[index] = {
              ...channelData[0].segmentList[index],
              startNode: routeSegmentList[index].startNode,
              endNode: routeSegmentList[index].endNode
            }
            if (channelData.length === 2) {
              channelData[1].segmentList[index] = {
                ...channelData[1].segmentList[index],
                startNode: routeSegmentList[index].startNode,
                endNode: routeSegmentList[index].endNode
              }
            }
            if (i.cableId) {
              this.graphicalCableData[i.cableId] = i.cable
            }
          })
          this.graphicalSegmentList = channelData
        }
        this.$nextTick(() => {
          this.$refs.bizGraphical && this.$refs.bizGraphical.formatData()
        })
      },
      // 下一步
      async next() {
        // console.log('this.formData', this.formData)
        this.formData.aPortData.regionName = this.getRegionName(this.formData.aStationId)
        this.formData.zPortData.regionName = this.getRegionName(this.formData.zStationId)
        if (this.step === 1) {
          this.$refs.stepOne.$refs.filterItem.getFormData()
          this.$refs.stepOne.$refs.firstForm.validate(valid => {
            if (valid) {
              if (this.formData.aNodeId === this.formData.zNodeId) {
                this.$message.error(this.$t('AZ_CANNOT_SAME'))
                return
              }
              let portIds = [this.formData.aPortData.portId, this.formData.zPortData.portId]
              if (this.formData.aPortData2) {
                portIds = [
                  ...portIds,
                  this.formData.aPortData2.portId,
                  this.formData.zPortData2.portId
                ]
              }
              bizOpenApi
                .firstVerify({
                  bizName: this.formData.bizName,
                  portId: portIds
                })
                .then(res => {
                  this.$refs.stepTwo && this.$refs.stepTwo.getRouteList('open')
                  this.step = 2
                })
            }
          })
        } else {
          this.isOtdrTesting = false
          if (!this.formData.routeData) {
            this.$message.error(this.$t('SELECT_ROUTE_SCHEME'))
            return
          }
          if (this.formData.channelData.some(i => i.isReach === false)) {
            this.$message.error(this.$t('CHANNEL_UNREACHABLE'))
            return
          }
          // 判断选中的通道AFS设备是否可用
          const checkeAfs = await checkAfs(this.formData, 'INTELLIGENT_CONNECT')
          if (!checkeAfs) return
          this.step = 3
        }
      },
      async save() {
        // 数据拼接
        console.log('this.formData', this.formData)
        // 判断otdr测试是否正在执行中
        if (this.isOtdrTesting) {
          this.$message.error(this.$t('CONFIRM_OPEN'))
          return
        }
        // 判断选中的通道AFS设备是否可用
        const checkeAfs = await checkAfs(this.formData, 'INTELLIGENT_CONNECT')
        if (!checkeAfs) return
        const formData = deepClone(this.formData)

        const bizChannelList = formData.channelData.map(i => {
          const transDirect =
            i.startPortId === formData.aPortData.portId
              ? formData.aPortData.funcType
              : formData.zPortData.funcType
          const cutoverData = i.cutoverList.map(j => {
            return {
              ...j,
              portName: j.port.bizName,
              connPortName: j.connPort.bizName
            }
          })
          const channelItem = {
            startPortId: i.startPortId,
            endPortId: i.endPortId,
            linkLoss: i.linkLoss,
            cutoverList: cutoverData,
            segmentList: i.segmentList,
            transDirect: this.transTable[transDirect]
          }
          return channelItem
        })
        const queryData = {
          bizChannelList: bizChannelList,
          bizOpen: {
            resourceCode: formData.resourceCode,
            bizName: formData.bizName,
            bizLevel: formData.bizLevel,
            endNodeId: formData.zNodeId,
            endStationId: formData.zStationId,
            isAutoRestore: false,
            isOtdrTest: false,
            startNodeId: formData.aNodeId,
            startStationId: formData.aStationId,
            segmentIdList: formData.routeData.segmentList.map(i => i.segmentId)
          },
          openType: this.formData.routeData.logicMatrix.length > 2 ? 'NORMAL' : 'INDEPENDENT',
          functionName: formData.functionName // 操作日志需要传此类型，判断是topo还是业务管理里执行的开通
        }
        // console.log(queryData)
        bizOpenApi.open(queryData).then(res => {
          this.step = 4
          this.$message.success(this.$t('ADD_SUCCESS'))
          this.close(true)
        })
      },
      // 上一步
      previous() {
        if (this.step === 2) {
          this.formData.channelData = null
          this.formData.routeData = null
          this.step--
        }
        if (this.step === 3) {
          if (
            this.$refs.otdrTestBtn.completed ||
            this.$refs.otdrTestBtn.failed ||
            this.isOtdrTesting
          ) {
            this.$confirm(this.$t('CONFIRM_PREVIOUS_STEP'), {
              type: 'warning',
              confirmButtonText: this.$t('OK_YES'),
              cancelButtonText: this.$t('OK_NO')
            })
              .then(() => {
                this.step--
              })
              .catch(() => {})
          } else {
            this.step--
          }
        }
      },
      close(load) {
        if (this.step === 3 && this.isOtdrTesting && load !== true) {
          this.$confirm(this.$t('CONFIRM_CANCLE_OPEN'), {
            type: 'warning',
            confirmButtonText: this.$t('OK_YES'),
            cancelButtonText: this.$t('OK_NO')
          })
            .then(() => {
              this.step = 1
              this.$emit('close', load)
            })
            .catch(() => {})
          return
        } else {
          this.$emit('close', load)
        }
        this.formData = this.$options.data().formData
      },
      // otdr测试状态改变
      taskChange(data) {
        this.isOtdrTesting = data
        this.$store.commit('setIsOtdrTesting', data)
      },
      // 获取区域/站点/机房
      getRegionName(stationId) {
        const stationData = this.baseRegionList.find(i => i.regionId === stationId)
        return stationData ? stationData.regionName : ''
      }
    }
  }
</script>

<style scoped></style>
